//
//  ConfirmOrderController.m
//  WuJieLive
//
//  Created by iMac on 2017/12/18.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "ConfirmOrderController.h"
#import "OrderAddressCell.h"
#import "OrderBottomView.h"
#import "OrderGetAddressCell.h"
#import "OrderContentCell.h"
#import "ProductionView.h"
#import "OrderDetailModel.h"
#import "OrderPayForController.h"
#import "TicketController.h"
#import "OrderTicketController.h"
#import "AddNewAddressController.h"
#import "ShoppingAddressController.h"

@interface ConfirmOrderController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) UITableView * tableview;
@property (nonatomic , strong) ProductionView * productionView;
@property (nonatomic , strong) UILabel * farePriceLabel;

@property (nonatomic , strong) OrderBottomView * orderBottomView;

@end

@implementation ConfirmOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)leftBtnAction:(UIButton *)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)setNavi
{
    self.title = @"确认订单";
}

-(void)setUI
{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 50) style:(UITableViewStyleGrouped)];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.view addSubview:self.tableview];
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderAddressCell" bundle:nil] forCellReuseIdentifier:@"OrderAddressCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderGetAddressCell" bundle:nil] forCellReuseIdentifier:@"OrderGetAddressCell"];
    [self.tableview registerClass:[OrderContentCell class] forCellReuseIdentifier:@"OrderContentCell"];
    self.orderBottomView = [[[NSBundle mainBundle] loadNibNamed:@"OrderBottomView" owner:self options:nil] lastObject];
    [self.view addSubview:self.orderBottomView];
    [self.orderBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.equalTo(self.view);
        make.height.offset(50);
    }];
    
    __weak typeof(self) weakSelf = self;
    self.orderBottomView.totalMoneyLabel.text = [NSString stringWithFormat:@"¥:%@",self.totalMoney];
    self.orderBottomView.faraLabel.text = [NSString stringWithFormat:@"(含运费:¥%@)",self.farePrice];
    self.orderBottomView.commitOrderBlock = ^{
        [weakSelf commitOrder];
    };
}

- (void)commitOrder
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken,@"order_info_redis_key":self.reKey};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/submit-pre-order",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            OrderPayForController * vc =  [[OrderPayForController alloc]init];
            vc.totalMonty = self.totalMoney;
            vc.orderIDs = responseObject[@"data"][@"order_ids"];
            vc.order_type = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 1;
    }else
    {
        return 3;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 1)
    {
        return self.orderArray.count * 121;
    }else
    {
        return 50;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
//        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        UITableViewCell *  cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"Cell"];
        cell.textLabel.font = FontSize(13);
        cell.textLabel.textColor = Color(51, 51, 51);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row == 0) {
                
            cell.textLabel.text = @"配送方式";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"邮费:%@",self.farePrice];
            cell.detailTextLabel.font = FontSize(14);
            cell.detailTextLabel.textColor = TextAssistColor;

        }else if (indexPath.row == 1)
        {
            cell.textLabel.text = @"优惠券";
            if (self.ticketModel.coupon_name.length > 0) {
                cell.textLabel.text = [NSString stringWithFormat:@"优惠券:%@",self.self.ticketModel.coupon_name];
                cell.detailTextLabel.textColor = TextAssistColor;
                cell.detailTextLabel.font = FontSize(14);
                cell.detailTextLabel.text = [NSString stringWithFormat:@"-¥%@",self.ticketModel.coupon_price];
            }
        }else
        {
            NSString * priceString = [NSString stringWithFormat:@"¥:%@",self.totalMoney];
            NSString * string = [NSString stringWithFormat:@"共%@件商品，合计:%@",self.goodsSum,priceString];
            NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc]initWithString:string];
            NSRange range = [string rangeOfString:priceString];
            [attributedString setAttributes:@{NSForegroundColorAttributeName:MainColor,NSFontAttributeName:FontSize(18)} range:range];
            
            NSRange tempRange = [string rangeOfString:[NSString stringWithFormat:@"共%@件商品，合计:",self.goodsSum]];
            [attributedString setAttributes:@{NSForegroundColorAttributeName:TextAssistColor,NSFontAttributeName:FontSize(13)} range:tempRange];
            
            cell.detailTextLabel.attributedText = attributedString;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }else if (indexPath.section == 0)
    {
        if (self.addressModel.address_id.length > 0) {
            OrderGetAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OrderGetAddressCell" forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell bindDataWithModel:self.addressModel];
            return cell;
        }else
        {
            OrderAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OrderAddressCell" forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }else
    {
        OrderContentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OrderContentCell" forIndexPath:indexPath];
        cell.dataArray = self.orderArray;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 10;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            if (self.orderArray.count > 0) {
                self.productionView = [[[NSBundle mainBundle] loadNibNamed:@"ProductionView" owner:self options:nil] lastObject];
                self.productionView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
                self.productionView.titleLabel.text = @"运费说明";
                OrderDetailModel * model = self.orderArray[0];
                [self.productionView configureTextViewWithDict:model.fare];
                self.productionView.scoreBtn.hidden = YES;
                self.productionView.scoreLabel.hidden = YES;
                self.productionView.rebackBtn.hidden = YES;
                self.productionView.rebackLabel.hidden = YES;
                [self.view addSubview:self.productionView];
            }
        }else if(indexPath.row == 1)
        {
            __weak typeof(self) weakSelf = self;
            OrderTicketController * vc = [[OrderTicketController alloc]init];
            vc.goods_redis_key = self.addressCouponKey;
            vc.block = ^(NSString *ticketID) {
                [weakSelf reloadWithTicketID:ticketID];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.section == 0){
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[OrderAddressCell class]]) {
            AddNewAddressController * vc = [[AddNewAddressController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            __weak typeof(self) weakSelf = self;
            ShoppingAddressController * vc = [[ShoppingAddressController alloc]init];
            vc.canClick = YES;
            vc.block = ^(NSString *addressID) {
                [weakSelf reloadWithID:addressID];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)reloadWithTicketID:(NSString *)ticketID
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.dict setObject:ticketID forKey:@"coupon_user_id"];
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/pre-confer-order",BaseUrl] para:self.dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            [self.ticketModel setValuesForKeysWithDictionary:responseObject[@"data"][@"coupon"]];
            self.totalMoney = responseObject[@"data"][@"total_price_format"];
            self.orderBottomView.totalMoneyLabel.text = [NSString stringWithFormat:@"¥:%@",self.totalMoney];
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)reloadWithID:(NSString *)addressID
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.dict setObject:addressID forKey:@"address_id"];
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/pre-confer-order",BaseUrl] para:self.dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            [self.addressModel setValuesForKeysWithDictionary:responseObject[@"data"][@"address"]];
            self.farePrice = responseObject[@"data"][@"fare_price_format"];
            self.orderBottomView.faraLabel.text = [NSString stringWithFormat:@"(含运费:¥%@)",self.farePrice];
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(OrderTicketModel *)ticketModel
{
    if (!_ticketModel) {
        _ticketModel = [[OrderTicketModel alloc]init];
    }
    return _ticketModel;
}


@end
